#include<stdio.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<netinet/in.h>//结构体，方便赋值
#include<stdlib.h>
#include<unistd.h>
#include "StdTcp.h"


struct TcpServer
{
    int sock;
};
Tcps *InitTcpServer(const char *ip, short int port)
{

    Tcps*s=(Tcps *)malloc(sizeof(Tcps));
    if(s==NULL)
    {
        printf("InitTcpServer malloc error!\n");
        return NULL;
    }

    s->sock=socket(AF_INET,SOCK_STREAM,0);
    if(s->sock<0)
    {
        perror("socket:");
        free(s);
        return NULL;
    }
    int on=1;
    if(setsockopt(s->sock,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int))<0)
    {
        perror("setsockopt:");
        free(s);
        return NULL;
    }

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(port);
    addr.sin_addr.s_addr=inet_addr(ip);

    if(bind(s->sock,(struct sockaddr*)&addr,sizeof(addr))<0)
    {
        perror("bind");
        free(s);
        return NULL;
    }
    if(listen(s->sock,10)<0)
    {
        perror("listen:");
        free(s);
        return NULL;
    }
    return s;
}

int TcpServerAccrpt(Tcps *s)
{

    int acceptSock=0;

    struct sockaddr_in addr;
    socklen_t len=1;
    if((acceptSock=accept(s->sock,(struct sockaddr*)&addr,&len))<0)
    {
        perror("acceptSock :");
        return -1;
    }
    return acceptSock;
}

void TcpServerSend(int ClientSock, void *ptr, size_t size)
{
    if(send(ClientSock,ptr,size,0)<0)
    {
        perror("send");
    }
}

void TcpServerRecv(int ClientSock, void *ptr, size_t size)
{
    if(recv(ClientSock,ptr,size,0)<0)
    {
        perror("recv:");
    }
}

void ClearTcpServer(Tcps *s)
{
    close(s->sock);
    free(s);
}

struct TcpClient
{
    int sock;
};

Tcpc *InitTcpClient(const char *ServerIp, short int ServerPort)
{
    Tcpc*c=(Tcpc*)malloc(sizeof(Tcpc));
    if(c==NULL)
    {
        perror("InitTcpClient:");
        return NULL;
    }
    c->sock=socket(AF_INET,SOCK_STREAM,0);
    if(c->sock<0)
    {
        perror("socket:");
        free(c);
        return NULL;
        
    }
    
    struct sockaddr_in ServerAddr;
    ServerAddr.sin_family=AF_INET;
    ServerAddr.sin_port=htons(ServerPort);
    ServerAddr.sin_addr.s_addr=inet_addr(ServerIp);
    if(connect(c->sock,(struct sockaddr*)&ServerAddr,sizeof(ServerAddr))<0)
    {
        perror("connect:");
        free(c);
        return NULL;
    }
    return c;
    
}

void TcpClientSend(Tcpc *c, void *ptr, size_t size)
{
    if(send(c->sock,ptr,size,0)<0)
    {
        perror("send:");
        
    }
}

void TcpClientRecv(Tcpc *c, void *ptr, size_t size)
{
    if(recv(c->sock,ptr,size,0)<0)
    {
        perror("recv:");
    }
}

void ClearTcpClient(Tcpc *c)
{
    close(c->sock);
    free(c);
}

